package com.lz.ovuola.web.interceptor;

import java.io.Serializable;
import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.lz.ovuola.util.annotation.ApiRestController;
import com.lz.ovuola.util.codec.EncryptionUtils;
import com.lz.ovuola.util.constant.RedisCacheConsts;
import com.lz.ovuola.util.exception.BusinessException;
import com.lz.ovuola.util.exception.msg.SysSecurityMsgEnum;
import com.lz.ovuola.util.redis.RedisTemplateRepository;
import com.lz.ovuola.util.threadlocal.UserContext;
import com.lz.ovuola.util.threadlocal.UserContextHolder;

/**
 * token校验拦截器
 * 
 * @author fz
 *
 */
@Component("resourceInterceptor")
public class ResourceInterceptor implements HandlerInterceptor {

	private Logger logger = LoggerFactory.getLogger("ResourceInterceptor");

	@Autowired
	private RedisTemplateRepository redisTemplateRepository;

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		// url资源访问过滤
		Method method = ((HandlerMethod) handler).getMethod();
		if (method.isAnnotationPresent(ApiRestController.class)) {
			ApiRestController apiRestController = (ApiRestController) method
					.getAnnotation(ApiRestController.class);
			if (!apiRestController.isRight())
				return true;
		}
		// token校验
		String authTemp = request.getHeader("Authorization");
		if (StringUtils.isEmpty(authTemp))
			throw new BusinessException(
					SysSecurityMsgEnum.USER_NOT_LOGIN.getStatus(),
					SysSecurityMsgEnum.USER_NOT_LOGIN.getMsg());
		checkToken(authTemp);
		return true;
	}

	/**
	 * 校验token
	 * 
	 * @param authTemp
	 */
	private void checkToken(String authTemp) {
		String authorization = new String(
				EncryptionUtils.base64Decode(authTemp));
		String[] params = authorization.split(":");
		if (params.length != 2)
			throw new BusinessException(
					SysSecurityMsgEnum.USER_NOT_LOGIN.getStatus(),
					SysSecurityMsgEnum.USER_NOT_LOGIN.getMsg());
		Serializable serializable = redisTemplateRepository.hget(
				RedisCacheConsts.OVUOLA_SECURITY_NAME_SPACE, params[0],
				params[1]);

		if (serializable instanceof UserContext) {
			UserContext userContext = (UserContext) serializable;
			UserContextHolder.set(userContext);
			logger.info("---user:{},token{},userId{}", params[0], params[1],
					userContext.getUserId());
		} else {
			throw new BusinessException(
					SysSecurityMsgEnum.USER_NOT_LOGIN.getStatus(),
					SysSecurityMsgEnum.USER_NOT_LOGIN.getMsg());
		}
	}

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		if (UserContextHolder.get() != null)
			UserContextHolder.remove();
	}

	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {

	}

}
